import React, { createContext, useContext, useState, useCallback, ReactNode, useEffect } from 'react';
import { Task, TaskContextType } from './types';
import taskService from '../services/taskService';

const TaskContext = createContext<TaskContextType | undefined>(undefined);

// 默认任务模板
const defaultTasks: Task[] = [
  {
    id: 'default-1',
    taskTitle: '欢迎使用任务管理系统',
    taskGuide: '这是一个默认任务，您可以开始添加自己的任务了',
    category: '默认',
    createdAt: new Date(),
  }
];

export const TaskProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchTasks = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const tasksData = await taskService.getTasks();
      setTasks(Array.isArray(tasksData) && tasksData.length > 0 ? tasksData : defaultTasks);
    } catch (err) {
      setError(err instanceof Error ? err.message : '获取任务列表失败');
      setTasks(defaultTasks);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  const addTask = useCallback(async (task: Omit<Task, 'id' | 'createdAt'>) => {
    try {
      setLoading(true);
      setError(null);
      const newTask = await taskService.createTask(task);
      if (!newTask) {
        throw new Error('添加任务失败：返回数据为空');
      }
      setTasks(prev => [...prev, newTask]);
    } catch (err) {
      setError(err instanceof Error ? err.message : '添加任务失败');
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  const updateTask = useCallback(async (id: string, task: Partial<Task>) => {
    try {
      setLoading(true);
      setError(null);
      const updatedTask = await taskService.updateTask(id, task);
      setTasks(prev => prev.map(t => t.id === id ? updatedTask : t));
    } catch (err) {
      setError(err instanceof Error ? err.message : '更新任务失败');
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  const deleteTask = useCallback(async (id: string) => {
    try {
      setLoading(true);
      setError(null);
      await taskService.deleteTask(id);
      setTasks(prev => prev.filter(t => t.id !== id));
    } catch (err) {
      setError(err instanceof Error ? err.message : '删除任务失败');
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);
  
  useEffect(() => {
    fetchTasks();
  }, [fetchTasks]);

  const value = {
    tasks,
    loading,
    error,
    fetchTasks,
    addTask,
    updateTask,
    deleteTask,
  };

  return <TaskContext.Provider value={value}>{children}</TaskContext.Provider>;
};

export const useTaskContext = () => {
  const context = useContext(TaskContext);
  if (context === undefined) {
    throw new Error('useTaskContext must be used within a TaskProvider');
  }
  return context;
};